package com.bdqn;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.FileOutputStream;
import java.io.IOException;

public class

Jd1 {
    public static void main(String[] args) {
        DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder db=dbf.newDocumentBuilder();
            Document document=db.parse("ch02/Short/src/Student.xml");
            Element crElm=document.createElement("Student");
            crElm.setAttribute("id","3");
            Element name=document.createElement("name");
            name.appendChild(document.createTextNode("王五"));
            Element course=document.createElement("course");
            course.appendChild(document.createTextNode("java"));
            Element score=document.createElement("score");
            score.appendChild(document.createTextNode("90"));
            crElm.appendChild(document.createTextNode("\n\t"));
            crElm.appendChild(name);
            crElm.appendChild(document.createTextNode("\n\t"));
            crElm.appendChild(course);
            crElm.appendChild(document.createTextNode("\n\t"));
            crElm.appendChild(score);
            crElm.appendChild(document.createTextNode("\n"));
            Element phone=(Element)document.getElementsByTagName("Students").item(0);
            phone.appendChild(crElm);
            phone.appendChild(document.createTextNode("\n"));
            //保存XML文件
            TransformerFactory factory=TransformerFactory.newInstance();
            Transformer transformer=factory.newTransformer();
            DOMSource domSource=new DOMSource(document);
            //设置字符编码
            transformer.setOutputProperty(OutputKeys.ENCODING,"UTF-8");
            StreamResult result= new StreamResult(new FileOutputStream("ch02/Short/src/Student.xml"));
            transformer.transform(domSource,result);
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TransformerConfigurationException e) {
            e.printStackTrace();
        } catch (TransformerException e) {
            e.printStackTrace();
        }

    }
}
